<script setup lang="tsx">
import type { ElDatePicker } from 'element-plus'
import PanchaDataManage from '../pancha-data/index.vue'
import PanchaPreview from '../pancha-preview/index.vue'
import PanchaReportTpl1 from '../pancha-report-tpl-1/index.vue'

defineOptions({ name: 'PanchaInformation' })

const props = withDefaults(defineProps<{
  /** 0-新增，1-模板 */
  type?: 0 | 1
  initialProtocol?: string
  initialYear?: string
  initialPoint?: number
  templateId?: number
  readonly?: boolean
  /** 锁定盘查，意味着协议、主体、年份不能修改，但是活动和子类别及数据可以修改，比如填报入口进来 */
  lockCarbonInventory?: boolean
  isTplViewing?: boolean
}>(), {
  type: 0,
})

const emit = defineEmits<{
  (e: 'open'): void
  (e: 'close'): void
  (e: 'clickOnPreviewButton'): void
  (e: 'clickOnDataManageButton', v?: { protocol: string, year: string, point: number }): void
  (e: 'clickOnDataAccButton'): void
  // 当模板应用成功后要销毁（模板只能使用一次）
  (e: 'destroyTemplateId'): void
}>()

const AsyncInformation = defineAsyncComponent(() => import('./async-information.vue'))

const datePickerRef = ref<InstanceType<typeof ElDatePicker>>()

const tanpanchaStore = useTanpanchaStore()
const userStore = useUserStore()
const visible = defineModel<boolean>({ required: true })

const protocol = ref()
const year = ref(props.initialYear)
const point = ref(props.initialPoint)

const startToloadOrCreate = ref(false)

const showDataManage = ref(false)
const showPanchaPreview = ref(false)
const showReportTpl = ref(false)

// 盘查ID (从子组件同步过来的)
const carbonInventoryId = ref()

// 核算的汇总数据
const summary = ref({
  totalCarbonEmission: 0,
  carbonEmission: 0,
  emissionReduction: 0,
})

const unit = computed(() => {
  return tanpanchaStore.panchaUnit
})

// 使用模板的情况不能修改协议
const disableProtocol = computed(() => {
  return props.isTplViewing || props.type === 1 || !!props.templateId || props.readonly || props.lockCarbonInventory
})

const disableYear = computed(() => {
  return props.isTplViewing || props.readonly || props.lockCarbonInventory
})

onMounted(() => {
  protocol.value = props.initialProtocol || tanpanchaStore.standards[0]?.value
  // console.log('mounted')
})
onBeforeUnmount(() => {
  // console.log('unmounted')
})

async function clickSaveTemplate() {
  const res = await ElMessageBox.prompt('请输入模板名称', '保存模板', {
    inputErrorMessage: '请输入模板名称，不能超过10个字',
    inputPattern: /^.{1,10}$/,
  }).catch(() => {})
  if (res && res.value) {
    if (carbonInventoryId.value) {
      carbonInventoryApi.saveAsTplWithCarbonInventory(
        res.value,
        carbonInventoryId.value,
      ).then(() => {
        ElMessage.success('操作成功')
      })
    }
  }
}

async function clickPreview() {
  await getSummary()
  await nextTick()
  showPanchaPreview.value = true
  emit('clickOnPreviewButton')
}

async function clickDataManage() {
  showDataManage.value = true
  emit('clickOnDataManageButton')
}

async function clickDataAcc() {
  await getSummary()
  await nextTick()
  showReportTpl.value = true
  emit('clickOnDataAccButton')
}

watchEffect(() => {
  if (unref(visible)) {
    open()
  }
  else {
    close()
  }
})

watch([year, protocol], async () => {
  startToloadOrCreate.value = false
  await nextTick()
  if (props.templateId && !props.isTplViewing) {
    checkCreateWithTemplate()
  }
  else {
    startToloadOrCreate.value = true
  }
})

function checkCreateWithTemplate() {
  carbonInventoryApi.checkCanUseTemplate({
    pointId: point.value!,
    protocolCode: protocol.value,
    dataTime: year.value as unknown as number,
  }).then((res) => {
    if (res.data === 0) {
      ElMessageBox.confirm(`是否在${year.value}年份应用模板创建盘查记录？`, '操作提示').then(() => {
        startToloadOrCreate.value = true;
        (datePickerRef.value as any)?.handleClose?.()
      }).catch(() => {
        (datePickerRef.value as any)?.handleClose?.()
      })
    }
    else {
      ElMessage.warning(`已经存在${year.value}年份的盘查记录！`)
    }
  })
}

async function refresh() {
  startToloadOrCreate.value = false
  await nextTick()
  startToloadOrCreate.value = true
}

async function handleDataManageSaveSuccess() {
  refresh()
}

async function getSummary() {
  const { data } = await carbonInventoryApi.calculateCarbonInventorySummary(
    carbonInventoryId.value,
  )
  summary.value = data
}

async function open() {
  point.value = props.initialPoint
  if (!props.isTplViewing) {
    year.value = props.initialYear ?? `${new Date().getFullYear()}`
  }
  else {
    year.value = props.initialYear
  }
  protocol.value = props.initialProtocol
  startToloadOrCreate.value = false
  await nextTick()
  if (!unref(point) || !unref(protocol)) {
    console.error(`
      pointId: ${unref(point)},
      protocolCode: ${unref(protocol)}
    `)
    throw new Error(`
      缺少参数 pointId, protocolCode
    `)
  }
  if (props.templateId && !props.isTplViewing) {
    checkCreateWithTemplate()
  }
  else {
    startToloadOrCreate.value = true
  }
  emit('open')
}
function close() {
  emit('close')
}
</script>

<template>
  <FullscreenModal v-model="visible">
    <div class="m-5 h-[calc(100%-2.5rem)] w-[calc(100%-2.5rem)] flex flex-col">
      <ElPageHeader class="flex-shrink-0 p-3" title="返回" @back="visible = false">
        <template v-if="!isTplViewing && carbonInventoryId" #extra>
          <ElButton v-if="!readonly" type="warning" plain @click="clickSaveTemplate">
            保存为模板
          </ElButton>
          <ElButton type="warning" @click="clickDataManage">
            数据管理
          </ElButton>
        </template>
      </ElPageHeader>
      <div class="relative flex-shrink-0 before:absolute before:left-0 before:right-0 before:top-0 before:h-1px before:w-full before:bg-gray-5 before:opacity-40 before:content-['']">
        <div class="flex">
          <div class="relative w-[280px] flex-shrink-0 p-3 after:absolute after:bottom-0 after:right-0 after:top-0 after:w-1px after:bg-gray-5 after:opacity-40 after:content-['']">
            <div v-if="disableProtocol" class="fs-14 flex items-center line-height-32px">
              <span>核算协议：</span>
              <span class="ml-3 opacity-80">{{ protocol }}</span>
            </div>
            <ElSelect v-else v-model="protocol" :disabled="disableProtocol" class="free" placeholder="请选择标准">
              <ElOption
                v-for="item in tanpanchaStore.standards"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </ElSelect>
          </div>
          <div class="flex-auto p-3">
            <ElForm inline class="flex gap-3" label-suffix="：">
              <ElFormItem label="核算主体" class="!m-0">
                <div class="opacity-80">
                  {{ point ? userStore.getPointNameById(point) : '' }}
                </div>
              </ElFormItem>
              <ElFormItem label="核算时间" class="!m-0">
                <div v-if="disableYear">
                  {{ year || '-' }}
                </div>
                <ElDatePicker v-else ref="datePickerRef" v-model="year" :editable="false" :clearable="false" :disabled="disableYear" type="year" value-format="YYYY" format="YYYY" />
              </ElFormItem>
            </ElForm>
          </div>
        </div>
      </div>
      <Suspense v-if="startToloadOrCreate && point">
        <AsyncInformation
          :point-id="point" :data-time="year"
          :protocol-code="protocol" :template-id="templateId"
          :readonly="readonly" :is-tpl-viewing="isTplViewing"
          @sync-summary="e => summary = e"
          @sync-carbon-inventory-id="e => carbonInventoryId = e"
          @after-template-id-applied="emit('destroyTemplateId')"
        />
        <template #fallback>
          <div class="p-3 opacity-80">
            加载中...
          </div>
        </template>
      </Suspense>
      <div v-if="!isTplViewing && carbonInventoryId" class="fs-14 flex flex-shrink-0 items-center p-3 line-height-none">
        <span>总排放量：</span>
        <span class="fs-20 text-green font-600">{{ summary.totalCarbonEmission }}</span>
        <span class="fs-12 ml-1 mr-8 mt-6px opacity-60">{{ unit }}</span>
        <span>总用能碳排：</span>
        <span class="fs-20 text-green font-600">{{ summary.carbonEmission }}</span>
        <span class="fs-12 ml-1 mr-8 mt-6px opacity-60">{{ unit }}</span>
        <span>减排：</span>
        <span class="fs-20 text-green font-600">{{ summary.emissionReduction }}</span>
        <span class="fs-12 ml-1 mr-8 mt-6px opacity-60">{{ unit }}</span>
        <ElButton type="success" class="ml-auto" plain @click="clickPreview">
          详情预览
        </ElButton>
        <ElButton type="success" @click="clickDataAcc">
          数据核算
        </ElButton>
      </div>

      <PanchaDataManage
        v-if="showDataManage" v-model="showDataManage"
        :carbon-inventory-id="carbonInventoryId"
        :readonly="readonly"
        @close="handleDataManageSaveSuccess"
      />
      <PanchaPreview
        v-if="showPanchaPreview" v-model="showPanchaPreview"
        :carbon-inventory-id="carbonInventoryId"
        @click-on-view-report="showReportTpl = true"
      />
      <PanchaReportTpl1
        v-if="showReportTpl" v-model="showReportTpl"
        :carbon-inventory-id="carbonInventoryId"
      />
    </div>
  </FullscreenModal>
</template>

<style>
.no-arrow-collapse-item {
  .el-collapse-item__arrow {
    display: none;
  }
}
</style>
